<?
class arrayXML extends gravy{
	public $text;
	public $arrays, $keys, $nodeFlag, $depth, $xmlParser;
	
	public function __construct(){
		parent::__construct();
	}
	
	/*Converts an array to an xml string*/
	function array2xml($array){
		//global $text;
		$this->text="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><data>";
		$this->text.=$this->arrayTransform($array);
		$this->text.="</data>";
		return($this->text);
	}
	
	function arrayTransform($array){
		foreach($array as $key=>$value){
			if(is_numeric($key)){
				$key="item";
			}
			$key=urlencode($key);
			#if($this->config->USE_ENCRYPTION){
			#	$key="field".$this->encrypt($key);
			#}
			if(!is_array($value)){
				$value=$value;
				if($this->config->USE_ENCRYPTION && ($key=="id" || substr($key,-3)=="_id")){
					$value=$this->encrypt($value);
				}
				$this->text.="<$key><![CDATA[$value]]></$key>";
			}else{
				$this->text.="<$key>";
				$this->arrayTransform($value);
				$this->text.="</$key>";
			}
		}
	}
	
	/*Transform an XML string to associative array "XML Parser Functions"*/
	function xml2array($xml){
		$this->depth=-1;
		$this->xmlParser=xmlParser_create();
		xml_set_object($this->xmlParser,$this);
		xmlParser_set_option ($this->xmlParser,XML_OPTION_CASE_FOLDING,0);
		xml_set_element_handler($this->xmlParser,"startElement","endElement");
		xml_set_character_data_handler($this->xmlParser,"characterData");
		xml_parse($this->xmlParser,$xml,true);
		xmlParser_free($this->xmlParser);
		return($this->arrays[0]);
	}
	
	function startElement($parser,$name,$attrs){
		$this->keys[]=$name; //We add a key
		$this->nodeFlag=1;
		$this->depth++;
	}
	
	function characterData($parser,$data){
		$key=end($this->keys);
		$this->arrays[$this->depth][$key]=$data;
		$this->nodeFlag=0; //So that we don't add as an array, but as an element
	}
	
	function endElement($parser,$name){
		$key=array_pop($this->keys);
		//If $nodeFlag==1 we add as an array, if not, as an element
		if($this->nodeFlag==1){
			$this->arrays[$this->depth][$key]=$this->arrays[$this->depth+1];
			unset($this->arrays[$this->depth+1]);
		}
		$this->nodeFlag=1;
		$this->depth--;
	}
}
?>